<template>
  <px-dialog v-model="visible" width="800px" @close="closeDrawer" @open="openDrawer">
    <template #header>
      <h3 style="font-weight: bold">关联系统</h3>
    </template>
    <template #default>
      <px-form ref="formRef" :model="formValue" label-position="right" label-width="80px">
        <EquipFactorySelect />
        <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
        <EquipSystemTree
          :isRequired="true"
          :className="formValue.className"
          :systemCode="formValue.systemCode"
          currentType="add"
          @changeAllSystemCodes="changeAllSystemCodes"
          @changeSystemCodes="changeSystemCodes"
          @clearSystem="clearSystem"
        />
      </px-form>
    </template>
    <template #footer>
      <px-button @click="closeDrawer">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
import EquipFactorySelect from "@/views/all/equip/components/EquipFactorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { addCategorySystem } from "@/api/equip/archive";
import { PxMessage } from "px-ui";
import { computed, ref, reactive, toRefs } from "vue";

// 调用父级-关闭抽屉、查询列表方法
const emits = defineEmits(["closeDrawer", "queryTable"]);

const formRef = ref();
const props = defineProps(["visible", "detailData"]);
const visible = computed(() => props.visible);

const state = reactive<any>({
  formValue: {
    className: "",
    systemCode: ""
  }
});
const { formValue } = toRefs(state);

const openDrawer = async () => {
  formValue.value.categoryId = props.detailData?.id;
};

// 关闭抽屉
const closeDrawer = () => {
  formRef.value.resetFields();
  emits("closeDrawer");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formValue.value));
      await addCategorySystem(params);
      PxMessage.success("关联成功");
      emits("closeDrawer");
      emits("queryTable");
    }
  });
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemCode"]);
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemCode = val3;
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
};
// 系统组件值改变触发
const clearSystem = val => {
  formRef.value?.resetFields(["systemCode"]);
};
</script>
<style lang="scss" scoped>
:deep(.px-select) {
  width: 100%;
}
</style>
